package win.larryzeal.jmx.jvm;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * 自定义的类加载器，务必注意：默认会委托parent进行加载！！
 *
 * 问题来了，如果我不使用parent进行加载呢？--不方便测试吧，因为默认的loadClass()方法都是双亲委托调用的。
 *
 * Created by 张少昆 on 2017/8/18 0018.
 */
public class MyClassLoader extends ClassLoader  {
	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException{

		byte[] data = getByteArray(name);
		if (data == null) {
			throw new ClassNotFoundException();
		}
		return defineClass(name, data, 0, data.length);
	}

	private byte[] getByteArray(String name){
		String filePath =   name.replace(".", File.separator);
		byte[] buf = null;
		try {
			FileInputStream in = new FileInputStream(filePath);
			buf = new byte[in.available()];
			in.read(buf);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return buf;
	}

	//测试下loadClass

	@Override
	protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException{

		System.out.println("loadClass过程：name="+name+", resolve="+resolve);
		return super.loadClass(name, resolve);
//		return null;
	}
}
